﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;

namespace MH3GAPP.Common
{
    class AccessDbCommand
    {
        /*
        #region 测试用
        public DataTable GetDataTable(string sqlStr)
        {
            OleDbCommand cmd = DbManager.GetInstance().GetOleConection().CreateCommand();
            cmd.CommandText = sqlStr;
            cmd.CommandType = CommandType.Text;

            OleDbDataReader reader = cmd.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Load(reader);
            return dt;
        }

        public DataSet GetDataSet(string sqlStr)
        {
            OleDbDataAdapter da = new OleDbDataAdapter(sqlStr, DbManager.GetInstance().GetOleConection());
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds;
        }
        #endregion
        */
        #region 查询
        /// <summary>
        /// 获取查询结果
        /// </summary>
        /// <param name="transaction">事务</param>
        /// <param name="sqlStr">SQL文</param>
        /// <returns>查询结果</returns>
        public DataTable ExecuteSqlDataTable(OleDbTransaction transaction, string sqlStr)
        {
            OleDbCommand cmd = DbManager.GetInstance().GetOleConection().CreateCommand();
            PrepareCommand(transaction, cmd, sqlStr);

            OleDbDataReader reader = cmd.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Load(reader);
            return dt;
        }
        #endregion

        #region 增/删/改
        /// <summary>
        /// 增/删/改
        /// </summary>
        /// <param name="transaction">事务</param>
        /// <param name="sqlStr">SQL文</param>
        /// <returns>执行返回码</returns>
        public int ExecuteSqlNonQuery(OleDbTransaction transaction, string sqlStr)
        {
            OleDbCommand cmd = DbManager.GetInstance().GetOleConection().CreateCommand();
            PrepareCommand(transaction, cmd, sqlStr);

            return cmd.ExecuteNonQuery();
        }
        #endregion

        #region 设置命令参数
        private void PrepareCommand(OleDbTransaction transaction, OleDbCommand command, string sqlStr)
        {
            if (command == null) throw new ArgumentNullException("command");
            if (sqlStr == null || sqlStr.Length == 0) throw new ArgumentNullException("strSQL");

            command.CommandText = sqlStr;
            if (transaction != null)
            {
                if (transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
                command.Transaction = transaction;
            }

            command.CommandType = CommandType.Text;

            return;
        }
        #endregion

    }
}
